package global

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
)

/*
*
Viper是一个第三方库，用来读取配置文件到类实体里
*/
func InitializeViper() *viper.Viper {
	viper := viper.New()
	switch gin.Mode() {
	case gin.DebugMode:
		viper.SetConfigName("config")
	case gin.ReleaseMode:
		viper.SetConfigName("config.release")
	default:
		viper.SetConfigName("config")
	}
	viper.AddConfigPath(".")
	viper.SetConfigType("yaml")

	err := viper.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %s \n", err))
	}
	viper.WatchConfig()
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)
		if err = viper.Unmarshal(&Config); err != nil {
			fmt.Println(err)
		}
	})
	if err = viper.Unmarshal(&Config); err != nil {
		fmt.Println(err)
	}
	return viper
}
